package com.xiaoyi.intentsdklibrary;

import android.content.Context;
import android.content.pm.FeatureInfo;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;

public class FlashUtils {
    private Context context;
    private Camera mCamera = null;
    private CameraManager manager;
    private boolean status = false;

    public FlashUtils(Context context2) {
        if (Build.VERSION.SDK_INT >= 21) {
            this.manager = (CameraManager) context2.getSystemService("camera");
        }
        this.context = context2;
    }

    public void open() {
        if (!this.status) {
            if (Build.VERSION.SDK_INT >= 23) {
                try {
                    this.manager.setTorchMode("0", true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                for (FeatureInfo featureInfo : this.context.getPackageManager().getSystemAvailableFeatures()) {
                    if ("android.hardware.camera.flash".equals(featureInfo.name)) {
                        if (this.mCamera == null) {
                            this.mCamera = Camera.open();
                        }
                        Camera.Parameters parameters = this.mCamera.getParameters();
                        parameters.setFlashMode("torch");
                        this.mCamera.setParameters(parameters);
                        this.mCamera.startPreview();
                    }
                }
            }
            this.status = true;
        }
    }

    public void close() {
        if (this.status) {
            if (Build.VERSION.SDK_INT >= 23) {
                try {
                    this.manager.setTorchMode("0", false);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            } else {
                Camera camera = this.mCamera;
                if (camera != null) {
                    camera.stopPreview();
                    this.mCamera.release();
                    this.mCamera = null;
                }
            }
            this.status = false;
        }
    }

    public void converse() {
        if (this.status) {
            close();
        } else {
            open();
        }
    }

    public boolean getState() {
        return this.status;
    }
}
